﻿using Fuse8.ContentManagementFramework.Administration.Models;
using Fuse8.ContentManagementFramework.BizFacade.Services;
using Fuse8.ContentManagementFramework.Domain;
using Fuse8.DomainFramework.Common.Locator;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Fuse8.ContentManagementFramework.Administration.Logic
{
    public class CmsPageTreeViewProvider : IFileViewProvider<CmsPage>
    {
        #region Fields

        private readonly CmsPageService _pageService = new CmsPageService();
        private readonly ICmsContext _currentPage = DependencyServiceLocator.Current.GetInstance<ICmsContext>();

        #endregion Fields

        #region IFileViewProvider<CmsPage> Members

        public CmsAdminFileItem GetRoot(int? id)
        {
            CmsAdminFileItem result = null;

            var allPages = _pageService.FindAll();

            if (allPages.Any())
            {
                result = new CmsAdminFileItem
                {
                    Name = "Not defined",
                    IsFile = true,
                    EntityId = 0,
                    Id = string.Empty,
                    NestedFileItems = GetNested(null, allPages, id).ToArray()
                };
            }

            return result;
        }

        #endregion IFileViewProvider<CmsPage> Members

        #region Methods

        protected virtual IList<CmsAdminFileItem> GetNested(int? parentId, IEnumerable<CmsPage> allPages, int? currentPageId)
        {
            var children = allPages.Where(p => p.ParentPageId == parentId);

            return children.Any() ?
                children
                    .Select(
                        p => new CmsAdminFileItem
                        {
                            Name = p.PageName,
                            IsFile = true,
                            EntityId = p.Id,
                            Id = p.PageUrl,
                            IsDisabled = currentPageId.HasValue && FindPageWithSameIdInTree(p, currentPageId.Value) != null,
                            NestedFileItems = GetNested(p.Id, allPages, currentPageId).ToArray()
                        })
                    .ToList() :
                new List<CmsAdminFileItem>();
        }

        protected virtual CmsPage FindPageWithSameIdInTree(CmsPage page, int currentPageId)
        {
            if (currentPageId == page.Id)
            {
                return page;
            }
            if (page.ParentPage != null)
            {
                page = FindPageWithSameIdInTree(page.ParentPage, currentPageId);
            }
            return null;
        }

        #endregion Methods
    }
}